package com.uex.dev.manage.admin.typehandler;

import com.google.common.base.Strings;
import com.google.gson.reflect.TypeToken;
import com.uex.dev.manage.common.utils.GsonUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;

/**
 * @author wangc
 * @create 2023/11/4
 * @description  DB文本字段转StringList
 */
public class ListStringTypeHandler extends BaseTypeHandler<List<String>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, GsonUtil.toJson(parameter));
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return convert(rs.getString(columnName));
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return convert(rs.getString(columnIndex));
    }

    @Override
    public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return convert(cs.getString(columnIndex));
    }

    private List<String> convert(final String columnValue) {
        if (Strings.isNullOrEmpty(columnValue)) {
            return Collections.emptyList();
        }
        return GsonUtil.fromJson(columnValue,new TypeToken<List<String>>() {}.getType());
    }
}
